<template>
  <div class="categories">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>分类管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加分类
          </el-button>
        </div>
      </template>
      
      <el-table :data="categories" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="sortOrder" label="排序" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="editCategory(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteCategory(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingId ? '编辑分类' : '添加分类'"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory" :loading="saving">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { getCategories, createCategory, updateCategory, deleteCategory } from '../api/category'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Categories',
  setup() {
    const categories = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const saving = ref(false)
    const editingId = ref(null)
    const formRef = ref(null)
    
    const form = ref({
      name: '',
      description: '',
      sortOrder: 0,
      status: 1
    })
    
    const rules = {
      name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' }
      ]
    }
    
    const loadCategories = async () => {
      loading.value = true
      try {
        const res = await getCategories()
        categories.value = res.data
      } catch (error) {
        ElMessage.error('加载分类失败')
      } finally {
        loading.value = false
      }
    }
    
    const showAddDialog = () => {
      editingId.value = null
      form.value = {
        name: '',
        description: '',
        sortOrder: 0,
        status: 1
      }
      dialogVisible.value = true
    }
    
    const editCategory = (row) => {
      editingId.value = row.id
      form.value = { ...row }
      dialogVisible.value = true
    }
    
    const saveCategory = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        saving.value = true
        
        if (editingId.value) {
          await updateCategory(editingId.value, form.value)
          ElMessage.success('更新成功')
        } else {
          await createCategory(form.value)
          ElMessage.success('创建成功')
        }
        
        dialogVisible.value = false
        loadCategories()
      } catch (error) {
        console.error('保存失败:', error)
      } finally {
        saving.value = false
      }
    }
    
    const deleteCategory = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除分类"${row.name}"吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await deleteCategory(row.id)
        ElMessage.success('删除成功')
        loadCategories()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    onMounted(() => {
      loadCategories()
    })
    
    return {
      categories,
      loading,
      dialogVisible,
      saving,
      editingId,
      form,
      rules,
      formRef,
      showAddDialog,
      editCategory,
      saveCategory,
      deleteCategory
    }
  }
}
</script>

<style scoped>
.categories {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>